
/* -*- C++ -*- */

//=============================================================================
/*
* @author Feloweria <380374483@qq.com>
* Copyright (C) Feloweria
*
* $ID 2014-07-010 18:04:45 PM
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details
*
* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>.
*
* @version 1.0
*/
//=============================================================================

#include "Base/StringConvertor.h"

FELOWRIA_BEGIN

inline
int32 WorkThread::GetID() const 
{
	return id;
}

template<typename Object, typename ...Types>
inline bool WorkThread::AddEvent(WorkThread *thread, Object *object, void (Object::*func)(Types...), Types...args)
{
	if(!thread || !object || !func)
		return false;

	if(thread == this)	
	{
		(object->*func)(args...);		
		return true;
	}
	
	if(thread->GetID() >= static_cast<int>(thread_list.size()))
		thread_list.resize(thread->GetID() + 1);
	
	if (thread->GetID() >= static_cast<int>(send_list.size()))
		send_list.resize(thread->GetID() + 1);

	EventQueue &event_queue = send_list[thread->GetID()];

	if(event_queue.size() >= EVENT_QUEUE_SIZE)
	{
		LOG_ERROR(String("Thread [") + StringConvertor<UTF8>::ToString(id) + String("] send_list is full"));
		return false;	
	}

	thread_list[thread->GetID()] = thread;
	event_queue.push_back(std::bind(func,object,args...));
	
	return true;
}


template<typename ...Types>
bool WorkThread::AddEvent(WorkThread *thread, void (*func)(Types...), Types...args)
{
	if(!thread || !func)
		return false;
	
	if(thread == this)	
	{
		(*func)(args...);
		return true;
	}

	if(thread->GetID() >= thread_list.size())
		thread_list.resize(thread->GetID() + 1);
	
	if(thread->GetID() >= send_list.size())
		send_list.resize(thread->GetID() + 1);

	EventQueue &event_queue = send_list[thread->GetID()];

	if(event_queue.size() >= EVENT_QUEUE_SIZE)
	{
		LOG_ERROR(String("Thread [") + StringConvertor<UTF8>::ToString(id) + String("] send_list is full"));
		return false;	
	}

	thread_list[thread->GetID()] = thread;
	event_queue.push_back(std::bind(func,args...));

	return true;
}

FELOWRIA_END
